package com.cp.admin.api.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cp.admin.api.entity.CodeEnum;
import com.cp.admin.api.entity.Result;
import com.cp.admin.api.entity.bo.GroupAdminBO;
import com.cp.admin.api.utils.PKGeneratorUtils;
import com.cp.admin.api.utils.RedisUtils;
import com.cp.admin.api.utils.StrUtils;
import com.cp.admin.modular.system.service.IUserService;
import com.cp.admin.modular.user.model.*;
import com.cp.admin.modular.user.service.*;
import com.cp.admin.modular.user.service.impl.UserInfoServiceImpl;
import com.cp.core.support.StrKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.abi.datatypes.Int;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/friend")
@Api(value = "好友操作", tags = "好友操作")
public class FriendController extends BaseController {
    @Autowired
    private IUserFriendService friendService;
    @Autowired
    private IUserFriendGroupService friendGroupService;
    @Autowired
    private IUserFriendApplyService friendApplyService;
    @Autowired
    private IUserFriendInfoService friendInfoService;
    @Autowired
    private IUserBasicsService userService;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IChatgroupInfoService chatgroupInfoService;
    @Autowired
    private IChatgroupService chatgroupService;
    @Autowired
    private IVipService vipService;
    @Autowired
    private IChatgroupApplyService chatgroupApplyService;


    @ApiOperation("申请好友")
    @RequestMapping(value = "/applyFriend", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "发起人ID", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "objectId", value = "对方ID", dataType = "String", required = true, paramType = "query")
    })
    public Result applyFriend(Long userId, Long objectId) {
        if (userId == null || objectId == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        UserBasics object = userService.selectById(objectId);
        if (object == null || object.getStatus() == 1) {
            return new Result(CodeEnum.FAIL_30001);
        }
        //添加好友申请表
        UserFriendApply apply = new UserFriendApply();
        apply.setId(PKGeneratorUtils.getInstance().nextId());
        apply.setUserId(userId);
        apply.setObjectId(objectId);
        apply.setStatus(0);
        apply.setCreateTime(new Date());
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DAY_OF_MONTH, 3);//设置三天过期时间
        apply.setOverdueTime(ca.getTime());
        if (friendApplyService.insert(apply)) {

            return new Result(apply);
        }
        return new Result(CodeEnum.FAIL);
    }

    @ApiOperation("添加好友")
    @RequestMapping(value = "/addFriend", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "申请记录ID", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "0 拒绝 1 同意 ", dataType = "String", required = true, paramType = "query")
            //@ApiImplicitParam(name = "groupId", value = "分组id", dataType = "String", required = true, paramType = "query")
    })
    public Result logout(Long id, Integer status, Long groupId) {
        if (id == null || status == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        UserFriendApply apply = friendApplyService.selectById(id);
        if (apply == null) {
            return new Result(CodeEnum.FAIL_30002);
        }
        if (apply.getStatus() != 0) {
            return new Result(CodeEnum.FAIL_40003);
        }
        if (groupId != null) {
            UserFriendGroup group = friendGroupService.selectById(groupId);
            if (group == null) {
                return new Result(CodeEnum.FAIL_40001);
            }
        }
        if (status == 0) {//不同意
            apply.setStatus(0);
            friendApplyService.updateById(apply);
        }
        if (status == 1) {//同意
            apply.setStatus(1);
            UserFriend friend = friendService.selectById(apply.getUserId());
            friend.setFriendNumber(friend.getFriendNumber() + 1);
            UserFriendGroup group = friendGroupService.selectById(groupId);
            group.setGroupNumber(group.getGroupNumber() + 1);
            UserFriendInfo info = new UserFriendInfo();
            info.setUserId(apply.getUserId());
            info.setFriendId(apply.getObjectId());
            info.setGroupId(groupId);
            info.setCreateTime(new Date());
            info.setIntimacy(0);//亲密度默认为0
            info.setStatus(1);
            info.setSpecial(0);
            if (friendApplyService.updateById(apply) &&
                    friendService.updateById(friend) &&
                    friendInfoService.insert(info) &&
                    friendGroupService.updateById(group)
            ) {
                return new Result(CodeEnum.SUCCESS);
            }
        }
        return new Result(CodeEnum.FAIL);
    }


    @ApiOperation("好友列表")
    @RequestMapping(value = "/friendList", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "分组ID", dataType = "String", required = true, paramType = "query")
    })
    public Result friendList(Long groupId) {
        if (groupId == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        List<UserFriendInfo> infos = friendInfoService.selectList(new EntityWrapper().eq("group_id", groupId).eq("status", 1));
        return new Result(infos);
    }

    @ApiOperation("拉黑好友")
    @RequestMapping(value = "/deleteFriend", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "friendId", value = "好友id", dataType = "String", required = true, paramType = "query")
    })
    public Result deleteFriend(Long userId, Long friendId) {
        if (userId == null || friendId == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        UserFriendInfo info = friendInfoService.selectOne(new EntityWrapper()
                .eq("user_id", userId)
                .eq("friend_id", friendId)
                .eq("status", 1));
        if (info == null) {
            return new Result(CodeEnum.FAIL_40004);
        }
        info.setStatus(-1);
        info.setUpdateTime(new Date());
        friendInfoService.updateById(info);
        return new Result(CodeEnum.SUCCESS);
    }

    @ApiOperation("分组管理")
    @RequestMapping(value = "/groupAdmin", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String", required = true, paramType = "query")
//            @ApiImplicitParam(name = "id", value = "分组ID", dataType = "String", required = true, paramType = "query"),
//            @ApiImplicitParam(name = "operation", value = "操作 0添加 1修改 -1删除", dataType = "String", required = true, paramType = "query"),
//            @ApiImplicitParam(name = "groupName", value = "分组名", dataType = "String", required = true, paramType = "query")
    })
    public Result groupAdmin(GroupAdminBO bo, Long userId) {
        if (bo.getOperation() == null) {
            return new Result(CodeEnum.FAIL_10001);
        }

        List<UserFriendGroup> result = friendGroupService.selectList(new EntityWrapper().eq("user_id", userId));
        if (bo.getOperation() == 0) {
            UserFriendGroup group = new UserFriendGroup();
            group.setId(PKGeneratorUtils.getInstance().nextId());
            group.setUserId(userId);
            group.setCreateTime(new Date());
            group.setGroupNumber(0);
            group.setStatus(0);
            if (bo.getGroupName() != null) {
                for (UserFriendGroup groups : result) {
                    if (groups.getGroupName() == bo.getGroupName()) {
                        return new Result(CodeEnum.FAIL_40002);
                    }
                }
                group.setGroupName(bo.getGroupName());
            } else {
                List<UserFriendGroup> defaultGroup = friendGroupService.selectList(new EntityWrapper().like("group_name", "默认分组"));
                group.setGroupName("默认分组" + defaultGroup.size() + 1);
            }
            if (friendGroupService.insert(group)) {
                UserFriend friend = new UserFriend();
                friend.setGroupNumber(friend.getGroupNumber() + 1);
                friendService.update(friend, new EntityWrapper().eq("user_id", group.getUserId()));
                return new Result(group);
            }
        }
        if (bo.getOperation() == 1) {
            if (bo.getId() == null || bo.getGroupName() == null) {
                return new Result(CodeEnum.FAIL_10001);
            }
            UserFriendGroup group = friendGroupService.selectById(bo.getId());
            for (UserFriendGroup groups : result) {
                if (groups.getGroupName() == bo.getGroupName()) {
                    return new Result(CodeEnum.FAIL_40002);
                }
            }
            group.setGroupName(bo.getGroupName());
            group.setUpdateTime(new Date());
            if (friendGroupService.updateById(group)) {
                return new Result(group);
            }
        }
        if (bo.getOperation() == -1) {
            if (bo.getId() == null) {
                return new Result(CodeEnum.FAIL_10001);
            }
            UserFriendGroup group = friendGroupService.selectById(bo.getId());
            group.setStatus(-1);
            if (friendGroupService.updateById(group)) {
                return new Result(group);
            }
        }
        return new Result(CodeEnum.SUCCESS);
    }


    @ApiOperation("分组列表")
    @RequestMapping(value = "/groupList", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user_id", value = "用户ID", dataType = "String", required = true, paramType = "query")
    })
    public Result groupList(Long userId) {
        if (userId == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        List<UserFriendGroup> groups = friendGroupService.selectList(new EntityWrapper().eq("user_id", userId));
        return new Result(groups);
    }

    @ApiOperation("移动分组")
    @RequestMapping(value = "/mobileGroup", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "friendId", value = "好友id", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "toGroupId", value = "移动后分组ID", dataType = "String", required = true, paramType = "query")
    })
    public Result mobileGroup(Long friendId, Long toGroupId) {
        if (friendId == null || toGroupId == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        UserFriendInfo info = friendInfoService.selectOne(new EntityWrapper().eq("friend_id", friendId));
        UserFriendGroup mygroup = friendGroupService.selectById(info.getGroupId());
        UserFriendGroup togroup = friendGroupService.selectById(toGroupId);
        if (info == null || mygroup == null | togroup == null) {
            return new Result(CodeEnum.FAIL);
        }
        info.setGroupId(toGroupId);
        info.setUpdateTime(new Date());
        if (info.getGroupId() != togroup.getId()) {
            mygroup.setGroupNumber(mygroup.getGroupNumber() - 1);
            togroup.setGroupNumber(togroup.getGroupNumber() + 1);
        }
        if (friendInfoService.updateById(info) && friendGroupService.updateById(mygroup) && friendGroupService.updateById(togroup)) {
            return new Result(CodeEnum.SUCCESS);
        }
        return new Result(CodeEnum.FAIL);
    }


    /**
     * vip才能创建聊天群
     **/
    @ApiOperation("创建群聊")
    @RequestMapping(value = "/createChatgroup", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "创建人id", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "chatgroupName", value = "聊天群名", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "chatgroupCity", value = "是否同城群 0不是 1是", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "enterCost", value = "进群费用", dataType = "String", required = true, paramType = "query")
    })
    public Result createChatgroup(Long userId, String chatgroupName, Integer chatgroupCity, BigDecimal enterCost) {
        if (userId == null || StrKit.isBlank(chatgroupName) || chatgroupCity == null || enterCost == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        Vip isVip = vipService.selectOne(new EntityWrapper().eq("user_id", userId));
        if (isVip.getStatus() != 1) {
            return new Result(CodeEnum.FAIL_20005);
        }
        if (enterCost.compareTo(new BigDecimal(0)) == -1) {
            return new Result(CodeEnum.FAIL_10008);
        }
        ChatgroupInfo info = new ChatgroupInfo();
        Long id = PKGeneratorUtils.getInstance().nextId();
        info.setId(id);
        info.setUserId(userId);
        info.setChatgroupCity(chatgroupCity);
        info.setChatgroupName(chatgroupName);
        info.setChatgroupNumber(1);
        info.setEnterCost(enterCost);
        info.setCreatTime(new Date());
        if (chatgroupInfoService.insert(info)) {
            Chatgroup user = new Chatgroup();
            user.setChatgroupId(id);
            UserInfo result = userInfoService.selectById(userId);
            user.setCreateTime(new Date());
            user.setUserId(userId);
            user.setStatus(1);
            if (chatgroupService.insert(user)) {
                return new Result(CodeEnum.SUCCESS);
            }
        }
        return new Result(CodeEnum.FAIL);
    }


    @ApiOperation("申请加入群聊")
    @RequestMapping(value = "/applyJoinGroup", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "申请人id", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "chatgroupId", value = "聊天群ID", dataType = "String", required = true, paramType = "query")
    })
    public Result applyJoinGroup(Long userId, Long chatgroupId) {
        if (userId == null || chatgroupId == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        ChatgroupInfo chat = chatgroupInfoService.selectById(chatgroupId);
        UserBasics user = userService.selectById(userId);
        if (chat == null || chat.getStatus() != 1) {
            return new Result(CodeEnum.FAIL_40005);
        }
        if (user.getPeasQuantity().compareTo(chat.getEnterCost()) == -1) {
            return new Result(CodeEnum.FAIL_10016);
        }
        ChatgroupApply apply = new ChatgroupApply();
        apply.setId(PKGeneratorUtils.getInstance().nextId());
        apply.setUserId(userId);
        apply.setChatgroupId(chatgroupId);
        apply.setCreateTime(new Date());
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DAY_OF_MONTH, 3);//设置三天过期时间
        apply.setOverdueTime(ca.getTime());
        apply.setStatus(0);
        if (chatgroupApplyService.insert(apply)) {//申请加群 申请人扣钱
            user.setPeasQuantity(user.getPeasQuantity().subtract(chat.getEnterCost()));
            if (userService.updateById(user)) {
                return new Result(CodeEnum.SUCCESS);
            }
        }
        return new Result(CodeEnum.FAIL);
    }

    @ApiOperation("群聊申请处理")
    @RequestMapping(value = "/applyProcess", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "applyId", value = "申请记录id", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "0未同意 1同意 -1过期", dataType = "String", required = true, paramType = "query")
    })
    public Result applyProcess(Long applyId, Integer status) {
        if (applyId == null || status == null) {
            return new Result(CodeEnum.FAIL_10001);
        }
        ChatgroupApply apply = chatgroupApplyService.selectById(applyId);
        if (apply == null) {
            return new Result(CodeEnum.FAIL_30002);
        }
        if (apply.getStatus() == -1) {
            return new Result(CodeEnum.FAIL_40003);
        }
        if (status == 1) {
            Chatgroup chater = new Chatgroup();
            chater.setUserId(apply.getUserId());
            chater.setStatus(1);
            chater.setCreateTime(new Date());
            chater.setChatgroupId(apply.getChatgroupId());
            apply.setStatus(1);
            ChatgroupInfo info = chatgroupInfoService.selectOne(new EntityWrapper().eq("id", apply.getChatgroupId()));
            info.setChatgroupNumber(info.getChatgroupCity() + 1);
            if (chatgroupService.insert(chater) &&
                    chatgroupApplyService.updateById(apply) &&
                        chatgroupInfoService.updateById(info)) {//申请通过 群主加钱

                ChatgroupInfo result1 = chatgroupInfoService.selectById(apply.getChatgroupId());
                UserBasics result2 = userService.selectById(result1.getUserId());
                result2.setPeasQuantity(result2.getPeasQuantity().add(result1.getEnterCost()));
                if (userService.updateById(result2)) {
                    return new Result(CodeEnum.SUCCESS);
                }
            }
        }
        if (status == 0) {//申请不通过 申请人反钱
            apply.setStatus(0);
            UserBasics result1 = userService.selectById(apply.getUserId());
            ChatgroupInfo result2 = chatgroupInfoService.selectById(apply.getChatgroupId());
            result1.setPeasQuantity(result1.getPeasQuantity().add(result2.getEnterCost()));
            if (chatgroupApplyService.updateById(apply) && userService.updateById(result1)) {
                return new Result(CodeEnum.SUCCESS);
            }
        }
        return new Result(CodeEnum.FAIL);
    }
}
